<?php
namespace Home\Controller;

require_once dirname(__FILE__).'/../../../../vendor/workerman/gatewayclient/Gateway.php';

use GatewayClient\Gateway;
use Think\Controller;

include_once("Common.php");
include_once("mysqlha.php");
header("Content-Type:text/html; charset=utf-8");

class UserController extends CommonController
{
    //信息
    public function sysmsg()
    {
        exit(getSuccessJson([], '查询成功'));

        $Model = M('activity');
        $data = $Model->Query("SELECT * FROM activity ORDER BY addtime desc");

        if ($data) {
            foreach ($data as $k => $v) {
                $site_path = $_SERVER['HTTP_HOST'] . substr($_SERVER['PHP_SELF'],0,stripos($_SERVER['PHP_SELF'],'apis/index.php')-1);

                if (strpos($v['content'], '/public/uploads/us/') !== false) {
                    $data[$k]['content'] = str_replace('/public/uploads/us/', $site_path . '/public/uploads/us/', $v['content']);
                }
            }
        }

        $data = array($data);
        echo getSuccessJson($data, '查询成功');
    }

    //获取超级会员充值信息
    public function getNewMsg()
    {
        /*$Model = M();

        $data = $Model->query("select content from sysinfomation where user_id=0 AND touser=0 AND is_read=0 AND DATE_ADD(`addtime`, INTERVAL 1 SECOND)>NOW();")[0];

        if ($data) {
            $message = json_encode(['code' => 200, 'action' => 'Home/User/getNewMsg', 'data' => $data]);
        } else {
            $message = json_encode(['code' => 400, 'action' => 'Home/User/getNewMsg', 'data' => []]);
        }*/

        $message = json_encode(['code' => 400, 'action' => 'Home/User/getNewMsg', 'data' => []]);

        Gateway::sendToAll($message);

    }

    //修改用户经纬度
    public function setJW()
    {
        $userid = $_REQUEST['userid'];
        $longitude = $_REQUEST['longitude'];
        $latitude = $_REQUEST['latitude'];
        $updateArr = array(
            "longitude" => $longitude,
            "latitude" => $latitude
        );
        update("user", $updateArr, "id=$userid");
    }

    //过滤词
    public function filter()
    {
        $userid = $_REQUEST['userid'];

        $Model = M();
        $user = $Model->Query("select * from user where id=" . $userid . "");
        //过滤词数组
        $filter = M("filter_word")->where('state=1')->getField('name', true);

        $fword = ['壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
        $regex = "/[a-z,A-Z,0-9]/";
        $replacement = "";
        $user[0]['slogan'] = preg_replace($regex, $replacement, $user[0]['slogan']);

        foreach ($filter as $v) {
            $user[0]['slogan'] = str_replace($v, '', $user[0]['slogan']);
            $user[0]['slogan'] = str_replace($fword, '', $user[0]['slogan']);
        }

        $user = array($user);
        echo getSuccessJson($user);
    }

    //更改相册查看权限
    public function imgauth()
    {
        $id = $_REQUEST['user_id'];
        $auth = $_REQUEST['auth'];

        if (!in_array($auth, ['0', '1', '2', '3'])) {
            $result = ['code' => 220, 'msg' => '操作失败,auth参数不正确'];
            $this->ajaxReturn($result);
        }

        $user = M('user')->where('id=' . $id)->find();

        if ($auth == 1) {
            if ($user['sex'] == '女') {
                if (!$user['attestation']) {
                    $result = ['code' => 220, 'msg' => '未认证'];
                    $this->ajaxReturn($result);
                }
            } else if ($user['sex'] == '男') {
                if ($user['vip_end_datetime'] < date('Y-m-d H:i:s')) {
                    $result = ['code' => 220, 'msg' => '非会员'];
                    $this->ajaxReturn($result);
                }
            }
            $res = M('user')->where('id=' . $id)->save(['img_auth' => $auth, 'photo_price' => $_REQUEST['price']]);
        } else {
            $res = M('user')->where('id=' . $id)->save(['img_auth' => $auth]);
        }

        if ($res) {
            $result = ['code' => 200, 'msg' => '操作成功'];
            $this->ajaxReturn($result);
        } else {
            $result = ['code' => 220, 'msg' => '操作失败'];
            $this->ajaxReturn($result);
        }
    }

    //通过邀请码注册 方案三
    public function invite()
    {
        exit;

        $phone = $_REQUEST['phone'] ? $_REQUEST['phone'] : "";
        $wechat = $_REQUEST['wechat'] ? $_REQUEST['wechat'] : "";
        $qq_openID = $_REQUEST['qq_openID'] ? $_REQUEST['qq_openID'] : "";

        $code = strtoupper($_REQUEST['code']);

        if ($phone) {

            $user = M('user')->where(['phone' => $_REQUEST['phone'], 'reg' => 1])->find();
            if ($user) {
                $this->ajaxReturn(['code' => 220, 'msg' => '手机号已注册']);
            }

            $invite = M("code")->where(['code' => $code, 'type' => 1, 'state' => 0])->find();

            if ($invite) {
                $this->ajaxReturn(['code' => 200, 'msg' => '邀请码正确']);
            } else {
                $invite = M("user")->where(['yqm' => $code])->find();
                if ($invite) {
                    $this->ajaxReturn(['code' => 200, 'msg' => '邀请码正确']);
                } else {
                    $this->ajaxReturn(['code' => 220, 'msg' => '邀请码错误']);
                }
            }
        } else if ($wechat) {

            $user = M('user')->where(['wechat' => $_REQUEST['wechat'], 'reg' => 1])->find();
            if ($user) {
                $this->ajaxReturn(['code' => 220, 'msg' => '微信号已注册']);
            }

            $invite = M("code")->where(['code' => $code, 'type' => 1, 'state' => 0])->find();

            if ($invite) {
                $this->ajaxReturn(['code' => 200, 'msg' => '邀请码正确']);
            } else {
                $invite = M("user")->where(['yqm' => $code])->find();
                if ($invite) {
                    $this->ajaxReturn(['code' => 200, 'msg' => '邀请码正确']);
                } else {
                    $this->ajaxReturn(['code' => 220, 'msg' => '邀请码错误']);
                }
            }
        } else if ($qq_openID) {

            $user = M('user')->where(['qq_openID' => $_REQUEST['qq_openID'], 'reg' => 1])->find();
            if ($user) {
                $this->ajaxReturn(['code' => 220, 'msg' => 'QQ号已注册']);
            }

            $invite = M("code")->where(['code' => $code, 'type' => 1, 'state' => 0])->find();

            if ($invite) {
                $this->ajaxReturn(['code' => 200, 'msg' => '邀请码正确']);
            } else {
                $invite = M("user")->where(['yqm' => $code])->find();
                if ($invite) {
                    $this->ajaxReturn(['code' => 200, 'msg' => '邀请码正确']);
                } else {
                    $this->ajaxReturn(['code' => 220, 'msg' => '邀请码错误']);
                }
            }
        } else {
            $this->ajaxReturn(['code' => 220, 'msg' => '参数不全']);
        }
    }

    //申请邀请码
    public function code()
    {
        exit;

        $city = $_REQUEST['city'] ? $_REQUEST['city'] : '';
        $where = $_REQUEST['where'] ? $_REQUEST['where'] : '';
        $weixin = $_REQUEST['weixin'] ? $_REQUEST['weixin'] : '';
        $recommend = $_REQUEST['recommend'];

        $phone = $_REQUEST['phone'];
        $password = $_REQUEST['password'];

        if (!isset($_REQUEST['type'])) {
            $result = ['code' => 220, 'msg' => '缺少type参数'];
            $this->ajaxReturn($result);
        }

        if ($_REQUEST['type'] == 1) {//新用户申请

            for ($i = 2; $i > 1; $i++) {
                $code = code();
                $test = M("code")->where(['code' => $code, 'state' => 0])->select();
                if (!$test) {
                    $i = 0;
                }
            }

            // 启动事务
            M()->startTrans();

            // 准备数据
            if ($_REQUEST['phone']) {
                $user = M('user')->where(['phone' => $_REQUEST['phone']])->find();

                if ($user) {
                    if ($user['reg']) {
                        $this->ajaxReturn(['code' => 220, 'msg' => '手机账号已存在']);
                    } else {
                        $result = M('code')->where(['user_id' => $user['id'], 'type' => 0])->find();
                        if ($result) {
                            $this->ajaxReturn(['code' => 220, 'msg' => '审核中']);
                        }
                    }
                } else {
                    M("user")->data(['phone' => $_REQUEST['phone'], 'password' => $_REQUEST['password'], 'sex' => '男', 'name' => '路人', 'reg' => 0])->add();
                }

                $user_id = M("User")->where('phone=' . $_REQUEST['phone'])->getField('id');
            } else if ($_REQUEST['wechat']) {
                $user = M('user')->where(['wechat' => $_REQUEST['wechat']])->find();

                if ($user) {
                    if ($user['reg']) {
                        $this->ajaxReturn(['code' => 220, 'msg' => '账号已存在']);
                    } else {
                        $result = M('code')->where(['user_id' => $user['id'], 'type' => 0])->find();
                        if ($result) {
                            $this->ajaxReturn(['code' => 220, 'msg' => '审核中']);
                        }
                    }
                } else {
                    $res = M("User")->data(['wechat' => $_REQUEST['wechat'], 'sex' => '男', 'name' => '路人', 'reg' => 0])->add();
                }

                $user_id = M("User")->where(['wechat' => $_REQUEST['wechat']])->getField('id');

            } else if ($_REQUEST['qq_openID']) {
                $user = M('user')->where(['qq_openID' => $_REQUEST['qq_openID']])->find();

                if ($user) {
                    if ($user['reg']) {
                        $this->ajaxReturn(['code' => 220, 'msg' => '账号已存在']);
                    } else {
                        $result = M('code')->where(['user_id' => $user['id'], 'type' => 0])->find();
                        if ($result) {
                            $this->ajaxReturn(['code' => 220, 'msg' => '审核中']);
                        }
                    }
                } else {
                    M("user")->data(['qq_openID' => $_REQUEST['qq_openID'], 'sex' => '男', 'name' => '路人', 'reg' => 0])->add();
                }

                $user_id = M("User")->where(['qq_openID' => $_REQUEST['qq_openID']])->getField('id');
            } else if ($_REQUEST['wb_openID']) {
                $user = M('user')->where(['wb_openID' => $_REQUEST['wb_openID']])->find();

                if ($user) {
                    if ($user['reg']) {
                        $this->ajaxReturn(['code' => 220, 'msg' => '账号已存在']);
                    } else {
                        $result = M('code')->where(['user_id' => $user['id'], 'type' => 0])->find();
                        if ($result) {
                            $this->ajaxReturn(['code' => 220, 'msg' => '审核中']);
                        }
                    }
                } else {
                    M("user")->data(['wb_openID' => $_REQUEST['wb_openID'], 'sex' => '男', 'name' => '路人', 'reg' => 0])->add();
                }

                $user_id = M("User")->where(['wb_openID' => $_REQUEST['wb_openID']])->getField('id');
            }


            $res1 = M("code")->data(['user_id' => $user_id, 'code' => $code, 'type' => 0])->add();

            $res2 = M("self_code")->data(['city' => $city, 'where' => $where, 'weixin' => $weixin, 'recommend' => $recommend, 'code' => $code])->add();

            if ($res1 !== false && $res2 !== false) {
                M()->commit();

                $result = ['code' => 200, 'user_id' => $user_id, 'msg' => '申请邀请码成功,待审核'];
                $this->ajaxReturn($result);
            } else {
                M()->rollback();

                $result = ['code' => 220, 'msg' => '申请邀请码失败'];
                $this->ajaxReturn($result);
            }
        } else if ($_REQUEST['type'] == 0) {//老用户申请

            if (!$_REQUEST['user_id']) {
                $result = ['code' => 220, 'msg' => 'user_id不正确'];
                $this->ajaxReturn($result);
            }

            for ($i = 2; $i > 1; $i++) {
                $code = code();
                $test = M("code")->where(['code' => $code, 'state' => 0])->select();
                if (!$test) {
                    $i = 0;
                }
            }

            $result = M("code")->data(['code' => $code, 'user_id' => $_REQUEST['user_id'], 'type' => 0])->add();

            if ($result) {
                $result = ['code' => 200, 'msg' => '申请邀请码成功,待审核'];
                $this->ajaxReturn($result);
            } else {
                $result = ['code' => 220, 'msg' => '申请邀请码失败'];
                $this->ajaxReturn($result);
            }
        }
    }

    //认证码生成
    public function authcode()
    {
        $id = $_REQUEST['user_id'];

        $code = code();

        $result = M("user")->where(['id' => $id])->save(['authcode' => $code]);

        if ($result) {
            $result = ['code' => 200, 'invite' => $code, 'msg' => '操作成功'];
            $this->ajaxReturn($result);
        } else {
            $result = ['code' => 220, 'msg' => '操作失败'];
            $this->ajaxReturn($result);
        }
    }

    //提交认证资料
    public function sendauth()
    {
        $id = $_REQUEST['user_id'];                  //用户id
        $rz_name = trim($_REQUEST['rz_name']);       //验证姓名
        $male = $_REQUEST['male'];                   //验证性别
        $ID_card = $_REQUEST['ID_card'];             //身份证号码
        $ID_card_img0 = $_REQUEST['ID_card_img0'];  //身份证正面照
        $ID_card_img1 = $_REQUEST['ID_card_img1'];  //身份证反面照

        if ($_FILES) {
            upcard();
        }

        //判断认证情况
        $identity = M('user')->Query("SELECT is_identity_authentication FROM user WHERE id=" . $id . ";");
        $identity = $identity[0]['is_identity_authentication'];

        //未验证流程
        if ($identity == 0 || $identity == 3) {
            $updateArr = [
                'rz_name' => $rz_name,
                'male' => $male,
                'idcard' => $ID_card,
                'is_identity_authentication' => 1,     //认证进度
                'attestation' => 1                    //认证方式
            ];

            if (M('user')->where('id=' . $id)->save($updateArr) !== false) {
                $result = ['code' => 200, 'data' => $updateArr, 'msg' => '操作成功，认证信息已提交'];
            } else {
                $result = ['code' => 220, 'msg' => '操作失败'];
            }
            $this->ajaxReturn($result);
        } else if ($identity == 1) {
            $result = ['code' => 220, 'msg' => '审核中'];
            $this->ajaxReturn($result);
        } else if ($identity == 2) {
            $result = ['code' => 220, 'msg' => '已审核成功'];
            $this->ajaxReturn($result);
        }
    }

    //查询普通认证进程 states : 0为未认证，1为待审核，2为验证通过，3为验证不通过
    public function isrenzheng()
    {
        $user_id = $_REQUEST['user_id'];
        $user = M()->Query("SELECT is_identity_authentication,sex FROM user where id=" . $user_id . ";");

        if (!empty($user)) {
            $data = [
                'is_identity_authentication' => $user[0]['is_identity_authentication'],
                'user_id' => $user_id,
                'sex' => $user[0]['sex']
            ];
            $result = ['code' => 200, 'result' => $data, 'msg' => '查询成功'];
        } else {
            $data = [
                'user_id' => $user_id
            ];
            $result = ['code' => 220, 'result' => $data, 'msg' => '查询失败,用户ID不正确'];
        }
        $this->ajaxReturn($result);
    }

    //图片阅后焚烧
    public function burn()
    {
        $user_id = $_REQUEST['user_id'];   //被查看用户ID
        $to_user = $_REQUEST['to_user'];   //操作用户ID
        $id = $_REQUEST['id'];           //图片ID

        $data = [
            'id' => $id,
            'user_id' => $user_id,
            'to_user' => $to_user
        ];

        $res = M('img_burn')->where(['id' => $id, 'to_user' => $to_user])->select();

        if ($res) {
            $result = ['code' => 200, 'msg' => '操作成功'];
            $this->ajaxReturn($result);
        } else {
            if (M('img_burn')->add($data)) {
                $result = ['code' => 200, 'msg' => '操作成功'];
                $this->ajaxReturn($result);
            } else {
                $result = ['code' => 220, 'msg' => '操作失败'];
                $this->ajaxReturn($result);
            }
        }
    }

    //查看红包图片扣除余额
    public function packetimg()
    {
        $user_id = $_REQUEST['user_id'];   //被查看用户ID
        $to_user = $_REQUEST['to_user'];   //操作用户ID
        $img_id = $_REQUEST['img_id'];     //图片ID
        $price = $_REQUEST['price'];       //图片查看价格
    
        $photo = M('user_img')->where(['id' => $img_id])->find();
    
        if ($photo) {
            $price = $photo['packet'];
    
            $img = M('packet_img')->where(['img_id' => $img_id, 'to_user' => $to_user])->select();
    
            if ($img) {
                $result = ['code' => 220, 'msg' => '操作失败,已支付过，无需重复操作'];
                $this->ajaxReturn($result);
            }
    
            $volley = M('user')->where('id=' . $to_user)->getField('volley');
    
            if ($volley < $price) {
                $result = ['code' => 220, 'msg' => '余额不足'];
                $this->ajaxReturn($result);
            } else {
                $volley = $volley - $price;
        
                $data = [
                    'user_id' => $user_id,
                    'to_user' => $to_user,
                    'img_id' => $img_id,
                    'price' => $price
                ];
        
        
                $name = M('user')->where(['id' => $to_user])->getField('name');
                $context = ['name' => $name, 'time' => time(), 'img_id' => $img_id, 'price' => $_REQUEST['price'], 'type' => 2];
                $arr = [
                    'to_user' => $user_id,
                    'uid' => $to_user,
                    'context' => json_encode($context),
                    'type' => 8
                ];
        
                M('sys_message')->data($arr)->add();
        
                // 启动事务
                M()->startTrans();

                D('VolleyDesc')->index($user_id, $price, '红包照片被查看', 1);
                D('VolleyDesc')->index($to_user, $price, '查看红包照片');

                $res3 = M('packet_img')->add($data);
        
                if ($res3 !== false) {
                    M()->commit();

                    // 推送
                    /*$datas = json_encode(['type' => 9, 'userid' => $to_user, 'name' => $name], JSON_UNESCAPED_UNICODE);
                    D('Push')->send(9, $user_id, '消息提醒', "{$name} 查看你的红包照片", $datas);*/
            
                    $result = ['code' => 200, 'data' => $data, 'msg' => '操作成功,已成功扣费'];
                    $this->ajaxReturn($result);
                } else {
                    M()->rollback();
            
                    $result = ['code' => 220, 'msg' => '操作失败'];
                    $this->ajaxReturn($result);
                }
            }
        } else {
            $result = ['code' => 220, 'msg' => '照片不存在'];
            $this->ajaxReturn($result);
        }
    }

    //查看付费相册扣除余额
    public function authimg()
    {
        $user_id = $_REQUEST['user_id'];   //被查看用户ID
        $to_user = $_REQUEST['to_user'];   //操作用户ID

        $user = M('user')->where('id=' . $user_id)->find();

        if ($user['img_auth'] != 1) {
            $result = ['code' => 220, 'msg' => '操作失败,不是付费相册'];
            $this->ajaxReturn($result);
        }

        $img = M('auth_img')->where(['user_id' => $user_id, 'to_user' => $to_user])->select();

        if ($img) {
            $result = ['code' => 220, 'msg' => '已支付过，无需重复操作'];
            $this->ajaxReturn($result);
        }

        $pd = M('vip_num')->where(['user_id' => $user_id, 'to_user' => $to_user, 'type' => 3])->select();

        if ($pd) {
            $result = ['code' => 220, 'msg' => '已支付过，无需重复操作'];
            $this->ajaxReturn($result);
        }

        $vip = M('user')->where('id=' . $to_user)->getField('vip_end_datetime');
        if ($vip > date('Y-m-d H:i:s')) {
            $num = M('vip_num')->where(['user_id' => $to_user, 'type' => 3, 'date' => date("Y-m-d")])->count();

            //会员配置权限次数
            $count = M('vip_config')->limit(1)->getfield('count');

            if (!$num) {
                $data = [
                    'user_id' => $user_id,
                    'to_user' => $to_user,
                    'price' => 0.00
                ];

                $name = M('user')->where(['id' => $user_id])->getField('name');
                $context = ['name' => $name, 'time' => time(), 'price' => 0.00, 'type' => 1];
                $context = json_encode($context);
                $arr = [
                    'to_user' => $user_id,
                    'uid' => $to_user,
                    'context' => $context,
                    'type' => 7
                ];
                M('sys_message')->add($arr);

                $res = M('auth_img')->add($data);
                if ($res !== false) {
                    $this->ajaxReturn(['code' => 200, 'msg' => '会员每天免费' . $count . '次查看', 'num' => $count]);
                } else {
                    $this->ajaxReturn(['code' => 220, 'msg' => '操作失败']);
                }
            } else {
                if ($num < $count) {
                    $data = [
                        'user_id' => $user_id,
                        'to_user' => $to_user,
                        'price' => 0.00
                    ];

                    $name = M('user')->where(['id' => $user_id])->getField('name');
                    $context = ['name' => $name, 'time' => time(), 'price' => 0.00, 'type' => 1];
                    $context = json_encode($context);
                    $arr = [
                        'to_user' => $user_id,
                        'uid' => $to_user,
                        'context' => $context,
                        'type' => 7
                    ];
                    M('sys_message')->add($arr);

                    $res = M('auth_img')->add($data);
                    if ($res !== false) {
                        $this->ajaxReturn(['code' => 200, 'msg' => '会员每天免费' . $count . '次查看', 'num' => ($count - $num)]);
                    } else {
                        $this->ajaxReturn(['code' => 220, 'msg' => '操作失败']);
                    }
                }
            }
        }

        $volley = M('user')->where('id=' . $to_user)->getField('volley');
        $price = M('user')->where('id=' . $user_id)->getField('photo_price');

        if ($volley < $price) {
            $result = ['code' => 220, 'msg' => '余额不足'];
            $this->ajaxReturn($result);
        } else {
            $volley = $volley - $price;

            $data = [
                'user_id' => $user_id,
                'to_user' => $to_user,
                'price' => $price
            ];


            $name = M('user')->where(['id' => $user_id])->getField('name');
            $context = ['name' => $name, 'time' => time(), 'price' => $_REQUEST['price'], 'type' => 1];
            $arr = [
                'to_user' => $user_id,
                'uid' => $to_user,
                'context' => json_encode($context),
                'type' => 7
            ];

            M('sys_message')->data($arr)->add();
            M('vip_num')->add(['user_id' => $user_id, 'to_user' => $to_user, 'type' => 3, 'date' => date('Y-m-d')]);

            // 启动事务
            M()->startTrans();

            D('VolleyDesc')->index($to_user, $price, '查看付费相册');

            $res = M('auth_img')->add($data);

            if ($res !== false) {
                M()->commit();

                $result = ['code' => 200, 'data' => $data, 'msg' => '操作成功,已成功扣费'];
                $this->ajaxReturn($result);
            } else {
                M()->rollback();

                $result = ['code' => 220, 'msg' => '操作失败'];
                $this->ajaxReturn($result);
            }
        }
    }

    //官方微信号
    public function customService()
    {
        $data = M('config')->where(['id' => ['gt', 0]])->getField('k, v');

        foreach ($data as $k => $v) {
            $v = str_replace('，', ',', $v);
            trim($v, ',');
            $data[$k] = explode(',', $v);
        }

        $result = ['code' => 200, 'result' => $data, 'msg' => '操作成功'];

        $this->ajaxReturn($result);
    }

    //电台广播列表
    public function sysDymanic()
    {
        $user_id = $_REQUEST['user_id'];

        $offten_city = M("user")->where('id=' . $user_id)->getField('offten_city');

        $dymanic = M('sys_message')->where("(to_user=" . $user_id . " and type in(10,12,13, 17)) or (dymanic_city='" . $offten_city . "' and uid <> " . $user_id . ")")->order('create_time desc')->select();


        //进入列表点赞 报名通知执行已读
        $res = M('sys_message')->where(['to_user' => $user_id, 'type' => ['in', [10,12, 13, 17]]])->save(['is_read' => 1]);

        $data = [];
        foreach ($dymanic as $k => $v) {
            if ($v['type'] == 4) {
                //进入列表广播执行已读
                $res = M('dymanic_read')->where(['dy_id' => $v['user_id'], 'userid' => $user_id])->find();
                if (!$res) {
                    M('dymanic_read')->data(['dy_id' => $v['user_id'], 'userid' => $user_id])->add();
                }

                $v['context'] = json_decode($v['context'], true);

                $head = M('user')->where(['id' => $v['uid']])->getField('head_portrait');
                $name = M('user')->where(['id' => $v['uid']])->getField('name');

                $dymanic[$k]['head'] = $head;

                $time = strtotime($v['addtime']);
                if (!$time) {
                    $time = "未知";
                }
                $diff = time() - $time;
                if ($diff < 60) {
                    $time = $diff . "秒前";
                } else if ($diff < 3600) {
                    $time = floor($diff / 60) . "分钟前";
                } else if ($diff < 86400) {
                    $time = floor($diff / 3600) . "小时前";
                } else if ($diff < (86400 * 7)) {
                    $time = floor($diff / 86400) . "天前";
                } else if ($diff < (86400 * 30)) {
                    $time = floor($diff / 86400 / 7) . "周前";
                } else if ($diff < (86400 * 366)) {
                    $time = floor($diff / 86400 / 30) . "个月前";
                } else if ($diff < (86400 * 366 * 3)) {
                    $time = floor($diff / 86400 / 365) . "年前";
                } else {
                    $time = date("Y-m-d H:i:s", $time);
                }

                $dymanic[$k]['addtime'] = $time;
                $dymanic[$k]['name'] = $name;

                $item = [
                    'head' => $head,
                    'id' => $v['uid'],
                    'name' => $name,
                    'dy_id' => $v['user_id'],
                    'addtime' => $v['create_time'],
                    'city' => $v['context']['fabu_city'],
                    'type' => $v['context']['type'],
                    'desc' => $v['context']['desc'],
                    'leixing' => 1
                ];
                $data[] = $item;
            } else if (($v['type'] == 12) || ($v['type'] == 13) || ($v['type'] == 17)) {

                $v['context'] = json_decode($v['context'], true);

                $head = M('user')->where(['id' => $v['uid']])->getField('head_portrait');
                $name = M('user')->where(['id' => $v['uid']])->getField('name');

                $dymanic[$k]['head'] = $head;

                $time = strtotime($v['addtime']);
                if (!$time) {
                    $time = "未知";
                }
                $diff = time() - $time;
                if ($diff < 60) {
                    $time = $diff . "秒前";
                } else if ($diff < 3600) {
                    $time = floor($diff / 60) . "分钟前";
                } else if ($diff < 86400) {
                    $time = floor($diff / 3600) . "小时前";
                } else if ($diff < (86400 * 7)) {
                    $time = floor($diff / 86400) . "天前";
                } else if ($diff < (86400 * 30)) {
                    $time = floor($diff / 86400 / 7) . "周前";
                } else if ($diff < (86400 * 366)) {
                    $time = floor($diff / 86400 / 30) . "个月前";
                } else if ($diff < (86400 * 366 * 3)) {
                    $time = floor($diff / 86400 / 365) . "年前";
                } else {
                    $time = date("Y-m-d H:i:s", $time);
                }

                $dymanic[$k]['addtime'] = $time;
                $dymanic[$k]['name'] = $name;

                $item = [
                    'head' => $head,
                    'id' => $v['uid'],
                    'name' => $name,
                    'dy_id' => $v['user_id'],
                    'addtime' => $v['create_time'],
                    'desc' => $v['context']['desc'],
                    'leixing' => 2
                ];
                $data[] = $item;
            } else if ($v['type'] == 10) {

                $v['context'] = json_decode($v['context'], true);

                $head = M('user')->where(['id' => $v['uid']])->getField('head_portrait');
                $name = M('user')->where(['id' => $v['uid']])->getField('name');

                $dymanic[$k]['head'] = $head;

                $time = strtotime($v['addtime']);
                if (!$time) {
                    $time = "未知";
                }
                $diff = time() - $time;
                if ($diff < 60) {
                    $time = $diff . "秒前";
                } else if ($diff < 3600) {
                    $time = floor($diff / 60) . "分钟前";
                } else if ($diff < 86400) {
                    $time = floor($diff / 3600) . "小时前";
                } else if ($diff < (86400 * 7)) {
                    $time = floor($diff / 86400) . "天前";
                } else if ($diff < (86400 * 30)) {
                    $time = floor($diff / 86400 / 7) . "周前";
                } else if ($diff < (86400 * 366)) {
                    $time = floor($diff / 86400 / 30) . "个月前";
                } else if ($diff < (86400 * 366 * 3)) {
                    $time = floor($diff / 86400 / 365) . "年前";
                } else {
                    $time = date("Y-m-d H:i:s", $time);
                }

                $dymanic[$k]['addtime'] = $time;
                $dymanic[$k]['name'] = $name;

                $item = [
                    'head' => $head,
                    'id' => $v['uid'],
                    'name' => $name,
                    'addtime' => $v['create_time'],
                    'desc' => $v['context']['desc'],
                    'leixing' => 3
                ];
                $data[] = $item;
            }
        }

        $result = ['code' => 200, 'data' => $data, 'msg' => '操作成功'];
        $this->ajaxReturn($result);
    }

    //阅后焚毁一键恢复
    public function resetburn()
    {
        $user_id = $_REQUEST['user_id'];

        $res = M('img_burn')->where(['user_id' => $user_id])->delete();

        if ($res !== false) {
            $result = ['code' => 200, 'msg' => '操作成功'];
            $this->ajaxReturn($result);
        } else {
            $result = ['code' => 220, 'msg' => '操作失败'];
            $this->ajaxReturn($result);
        }
    }

    //申请查看用户相册
    public function requestimg()
    {
        $user_id = $_REQUEST['user_id'];
        $to_user = $_REQUEST['to_user'];
        $image = I('image');

        $data = [
            'user_id' => $user_id,
            'to_user' => $to_user,
            'pic' => $image,
        ];
        $res = M('img_request')->add($data);

        $name = M('user')->where(['id' => $to_user])->getField('name');

        $context = ['name' => $name, 'desc' => "请求查看您的详情页", 'pic' => $image, 'type' => 1];
        $arr = [
            'to_user' => $user_id,
            'uid' => $to_user,
            'context' => json_encode($context,JSON_UNESCAPED_UNICODE),
            'type' => 6
        ];
        M('sys_message')->data($arr)->add();

        if ($res) {
            // 推送
            /*$datas = json_encode(['type' => 7, 'userid' => $user_id, 'name' => $name], JSON_UNESCAPED_UNICODE);
            D('Push')->send(7, $to_user, '消息提醒', "{$name} 请求查看您的相册", $datas);*/

            $result = ['code' => 200, 'msg' => '操作成功'];
            $this->ajaxReturn($result);
        } else {
            $result = ['code' => 220, 'msg' => '操作失败'];
            $this->ajaxReturn($result);
        }
    }

    //申请查看相册验证用户列表
    public function requestlist()
    {
        $user_id = $_REQUEST['user_id'];

        //进入列表执行已读
        M('sys_message')->where(['to_user' => $user_id, 'type' => 6])->save(['is_read' => 1]);

        //$data = M('img_request')->where(['user_id' => $user_id])->order('time desc')->select();

        $data = M()->Query("select * from img_request where user_id = " . $user_id . " or to_user = " . $user_id . " order by time desc");

        $con = [];
        foreach ($data as $k => $v) {
            if ($v['user_id'] == $user_id) {
                $user = M('user')->where(['id' => $v['to_user']])->find();
                $item = [
                    'id' => (int)$v['id'],
                    'user_id' => (int)$v['to_user'],
                    'name' => $user['name'],
                    'head' => $user['head_portrait'],
                    'pic' => $v['pic'],
                    'addtime' => timestr($v['addtime']),
                    'desc' => '请求查看您的相册',
                    'state' => (int)$v['state'],
                    'type' => 6,
                    'self' => 1     # 相册拥有者
                ];
            } else {
                $user = M('user')->where(['id' => $v['user_id']])->find();
                $item = [
                    'id' => (int)$v['id'],
                    'user_id' => (int)$v['user_id'],
                    'name' => $user['name'],
                    'head' => $user['head_portrait'],
                    'pic' => $v['pic'],
                    'addtime' => timestr($v['addtime']),
                    'desc' => '的相册',
                    'state' => (int)$v['state'],
                    'type' => 6,
                    'self' => 0     # 申请者
                ];
            }

            $con[] = $item;
        }

        $result = ['code' => 200, 'data' => $con, 'msg' => '操作成功'];
        $this->ajaxReturn($result);
    }

    //申请查看相册验证通过验证
    public function agreeimg()
    {
        $id = $_REQUEST['id'];

        $res = M('img_request')->where(['id' => $id])->save(['time' => date('Y-m-d H:i:s'), 'state' => 1]);

        $user_id = M('img_request')->where(['id' => $id])->getField('user_id');
        $to_user = M('img_request')->where(['id' => $id])->getField('to_user');
        $name = M('user')->where(['id' => $user_id])->getField('name');

        $context = ['name' => $name, 'desc' => "已通过你的查看申请，有效期15天", 'type' => 2];
        $arr = [
            'to_user' => $to_user,
            'uid' => $user_id,
            'context' => json_encode($context,JSON_UNESCAPED_UNICODE),
            'type' => 6
        ];
        M('sys_message')->data($arr)->add();

        if ($res) {
            $result = ['code' => 200, 'msg' => '操作成功'];
            $this->ajaxReturn($result);
        } else {
            $result = ['code' => 220, 'msg' => '操作失败'];
            $this->ajaxReturn($result);
        }
    }

    public function syslist($user_id)
    {
        $user = M('user')->field('sex, age, register_datetime')->cache(86400)->where(['id' => $user_id])->find();

        $channel = $user['sex'] == '男' ? [1,2] : [1,3];
        $where = ['channel' => ['in', $channel], 'type' => ['in', [0,30,31,32]], 'sys_channel' => 1, 'to_user' => ['in', [0, $user_id]]];
        $age = $user['age'] ?? 0;
        $where['_string'] = "(is_top = 1 or create_time >= '" . $user['register_datetime'] . "') and ((age_min <= $age and age_max >= $age) or (age_min <= $age and age_max = 0) or (age_min = 0 and age_max = 0))";
        // exit($where['_string']);
        $message = M('sys_message')->where($where)->order('is_top desc, id desc')->limit(20)->getField('id', true);
        
        if ($message) {
            $read_count = M('sys_message_read')->where(['user_id' => $user_id, 'message_id' => ['in', $message]])->count();
    
            $count = count($message) - $read_count;
        } else {
            $count = 0;
        }
        $content = '';

        if ($count) {
            $newest = M('sys_message')->where($where)->order('is_top desc, id desc')->limit(1)->find();
            if ($newest) {
                if ($newest['type'] == 0) {
                    if ($newest['context']) {
                        $content = mb_substr(strip_tags(json_decode($newest['context'], true)['desc']), 0, 30) . '...';
                    }
                } else if ($newest['type'] == 30) {
                    $content = '商品推荐';
                } else if ($newest['type'] == 31) {
                    if ($newest['context']) {
                        $content = mb_substr(strip_tags(json_decode($newest['context'], true)['content']), 0, 30) . '...';
                    }
                } else if ($newest['type'] == 32) {
                    if ($newest['context']) {
                        $content = mb_substr(strip_tags(json_decode($newest['context'], true)['name']), 0, 5) . ' 向你申请解除拉黑';
                    }
                }
            }
        }
        $item = [
            'id' => 1,
            'pic' => '/public/style/api/img/system/tongzhi.png',
            'name' => '系统通知',
            'content' => $content,
            'count' => $count
        ];
        $data[] = $item;

        /*$contain = [
            'id' => 1,
            'pic' => 'icon.png',
            'name' => '看过我的',
            'content' => '',
            'data' => []
        ];

        $count = M('see_record')->where(['user_id' => $user_id, 'is_read' => 0])->count();

        if ($count) {
            $contain['content'] = "有{$count}人看过你";
            $contain['data'] = json_encode(['count' => $count]);
        }

        $data[] = $contain;*/

        /*$config = M('config_system')->where(['title' => ['in', ['family_switch', 'cluster_switch']]])->getField('title, content');

        if (intval($config['family_switch'])) {
            $contain = [
                'id' => 2,
                'pic' => '/public/style/api/img/cluster/family.png',
                'name' => '家族',
                'content' => '有家族不孤单，我们是相亲相爱的一家人',
                'data' => []
            ];

            $ids = M('cluster_user')->where(['user_id' => $user_id, 'status' => 1])->getField('cluster_id', true);

            if ($ids) {
                $cluster_id = M('cluster')->where(['types' => 1, 'id' => ['in', $ids], 'status' => 1])->getField('id');

                if ($cluster_id) {
                    $contain['data'] = json_encode(['cluster_id' => $cluster_id]);
                }
            }

            $data[] = $contain;
        }


        if (intval($config['cluster_switch'])) {
            $contain = [
                'id' => 3,
                'pic' => '/public/style/api/img/cluster/cluster.png',
                'name' => '群聊派对',
                'content' => '',
                'data' => []
            ];

            $count = M('cluster')->where(['types' => 2, 'status' => 1])->sum("count");

            if ($count) {
                $contain['content'] = "已有{$count}人在这里嗨";
                $contain['data'] = json_encode(['count' => $count]);
            }

            $data[] = $contain;
        }*/
        
        if ($user['sex'] == '女') {
            /*$unread_uid = M('privatechat')->where(['type' => ['neq', -1], 'single' => ['neq', 1], 'userid' => $user_id, 'isRead' => 0])->getField('touserid', true);
            $chat_uid = M('privatechat')->where(['type' => ['neq', -1], 'single' => ['neq', 1], 'userid' => ['in', $unread_uid], 'touserid' => $user_id])->getField('userid', true);
            $chat_uid = $chat_uid ?: [];
            $not_reply = array_diff($unread_uid, $chat_uid);*/

            //if ($not_reply) {
            if (true) {
                $contain = [
                    'id' => 4,
                    'pic' => '/public/style/api/img/cluster/cluster.png',
                    'name' => '未回复',
                    'content' => '没回复的人都在这里哦',
                    'data' => []
                ];

                $data[] = $contain;
            }
        }elseif($user['sex'] == '男') {
            // $zhaohucount = M()->query("select sum(unread) as count from ((SELECT user_unread as unread FROM chat_lists WHERE user_id = $user_id and user_delete = 0 and another_first = 1) UNION ALL (SELECT another_unread as unread FROM chat_lists WHERE another_id = $user_id and another_delete = 0 and user_first = 1)) as a");
            
            
            $zhoahu1 =  M('chat_lists')->where(['user_id'=>$user_id,'user_delete'=>0,'another_first'=>1])->sum('user_unread');
            $zhoahu2 =  M('chat_lists')->where(['another_id'=>$user_id,'another_delete'=>0,'user_first'=>1])->sum('another_unread');
            $contain = [
                'id' => 4,
                'pic' => '/public/style/api/img/cluster/cluster1.png',
                'name' => '搭讪消息',
                'content' => '跟你打招呼的人都在这里哦',
                'data' => [],
                // 'count' => $zhaohucount[0]['count']
                'count' => $zhoahu1+$zhoahu2
            ];

            $data[] = $contain;
        }


        $message = json_encode([
            "code" => 200,
            "action" => 'Home/User/syslist',
            'data' => $data
        ]);

        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $user_id, $message);
    }

    //评价列表
    public function evalist()
    {
        $user_id = $_REQUEST['user_id'];

        //进入评价列表，执行已读
        M('pingjia')->where(['to_user' => $user_id])->save(['is_read' => 1]);

        $pingjia = M('pingjia')->where(['to_user' => $user_id])->order('time desc')->select();
        $evalist = M('evaluate_default')->getField('id,content');

        foreach ($pingjia as $k => $v) {
            $name = M('user')->where(['id' => $v['user_id']])->getField('name');
            $head = M('user')->where(['id' => $v['user_id']])->getField('head_portrait');
            $content = json_decode($v['content'], true);
            $arr = [];
            foreach ($content as $k1 => $v1) {
                $arr[] = $evalist[$v1];
            }

            $time = timestr($v['time']);


            $item = [
                'id' => $v['user_id'],
                'name' => $name,
                'head' => 'syshead.php',
                'content' => $arr,
                'addtime' => $time
            ];
            $data[] = $item;
        }

        $result = ['code' => 200, 'data' => $data, 'msg' => '操作成功'];
        $this->ajaxReturn($result);
    }

    // 系统通知列表
    public function tongzhi($user_id)
    {
        $user = M('user')->field('sex,age, register_datetime')->cache(86400)->where(['id' => $user_id])->find();
    
        // $channel = $user['sex'] == '男' ? [1,2] : [1,3];
        // $where = ['channel' => ['in', $channel], 'type' => ['in', [0,30,31,32]], 'sys_channel' => ['in', [0, getenv('APP_CHANNEL')]], 'to_user'=>['in', [0, $user_id]]];
        // $age = $user['age'] ?? 0;
        // // $where['_string'] = "(is_top = 1 or create_time >= '" . $user['register_datetime'] . "') and ((age_min <= $age and age_max >= $age) or (age_min <= $age and age_max = 0) or (age_min = 0 and age_max = 0))";
        // $where['_string'] = "((age_min <= $age and age_max >= $age) or (age_min <= $age and age_max = 0) or (age_min = 0 and age_max = 0))";

        $where = ['channel'=>1,'type' =>0];
        $data = M('sys_message')->where($where)->order('is_top desc, id desc')->limit(20)->select();
        
        if ($data) {
            $message_ids = array_column($data, 'id');
            $read_message_ids = M('sys_message_read')->where(['user_id' => $user_id, 'message_id' => ['in', $message_ids]])->getField('message_id', true);
    
            $reads = [];
            foreach ($data as $k => $v) {

                $time = timestr($v['create_time']);
                $goods = [];
                $url = '';
                if ($v['type'] == 0) {
                    $context = out_content(json_decode($v['context'], true)['desc']);
                } else if ($v['type'] == 30){
                    $goods = M('mall_goods')->field('id,image,name,price')->find($v['context']);
                    $context = '商品推荐:' . $goods['name'];
                } else if ($v['type'] == 31){
                    $json = json_decode($v['context'], true);
                    $context = $json['content'];
                    $url = $json['url'];
                } else if ($v['type'] == 32) {
                    $json = json_decode($v['context'], true);
                    $context = $json['state'];
                }
                $data[$k] = [
                    'content' => $context,
                    'goods' => $goods,
                    'url' => $url,
                    'type' => $v['type'],
                    'uid' => $v['uid']??'',
                    'id' => $v['id'],
                    'addtime' => $time,
                    'context' => $json??''
                ];
        
                if (!in_array($v['id'], $read_message_ids)) {
                    $reads[] = ['message_id' => $v['id'], 'user_id' => $user_id];
                }
            }
    
            if (!empty($reads)) {
                M('sys_message_read')->addAll($reads);
        
                // A('Privatechat')->getreadcount(json_encode(['user_id' => $user_id]));
            }
        }
        
        $data = $data ?: [];

        $this->ajaxReturn(['code' => 200, 'data' => $data]);
    }

    //收益列表
    public function imgsylist()
    {
        $user_id = $_REQUEST['user_id'];

        M()->startTrans();
        // 准备数据
        $res1 = M('auth_img')->where(['user_id' => $user_id])->save(['is_read' => 1]);
        $res2 = M('packet_img')->where(['user_id' => $user_id])->save(['is_read' => 1]);

        if ($res1 !== false && $res2 !== false) {
            M()->commit();
        } else {
            M()->rollback();
        }


        $auth = M('sys_message')->where(['type' => ['in', '7,8'], 'to_user' => $user_id])->order('create_time desc')->select();

        foreach ($auth as $k => $v) {
            $context = json_decode($v['context'], true);

            $head = M('user')->where('id', $v['uid'])->getField('head_100');

            $item = [
                'name' => $context['name'],
                'head' => $head,
                'time' => timestr(date('Y-m-d H:i:s', $context['time'])),
                'price' => $context['price'],
                'type' => $context['type']
            ];

            $data[] = $item;
        }

        $result = ['code' => 200, 'data' => $data, 'msg' => '操作成功'];
        $this->ajaxReturn($result);
    }

    //执行已读
    public function isread()
    {
        $user_id = $_REQUEST['user_id'];
        $id = $_REQUEST['id'];

        if ($id == 1) {
            /*	$to_user = M('attention')->where(['user_id'=>$user_id])->getfield('to_user',true);

			M('sys_message')->where(['type'=>9])->save(['is_read'=>1]);
			$res = M('sys_message')->where(['uid'=>['in',$to_user],'type'=>4])->save(['is_read'=>1]);


			if($res !== false){
				$result = ['code' => 200,'msg' =>'操作成功'];
		        $this->ajaxReturn($result);
			}else{
				$result = ['code' => 220,'msg' =>'操作失败'];
		        $this->ajaxReturn($result);
			}*/

            $dylist = M('dymanic')->where(['type' => 2])->getField('dy_id', true);

            foreach ($dylist as $k => $v) {
                $res = M('sys_dymanic_read')->where(['dy_id' => $v, 'userid' => $user_id])->find();
                if (!$res) {
                    $res = M('sys_dymanic_read')->data(['dy_id' => $v, 'userid' => $user_id])->add();
                }
            }
            $res = M('sys_message')->where(['to_user' => $user_id, 'type' => ['in', [4, 10, 12, 13, 17]]])->save(['is_read' => 1]);

            // $res = M('sys_message')->where(['to_user'=>$user_id,'type'=>4])->save(['is_read'=>1]);

            if ($res !== false) {
                $result = ['code' => 200, 'msg' => '操作成功'];
                $this->ajaxReturn($result);
            } else {
                $result = ['code' => 220, 'msg' => '操作失败'];
                $this->ajaxReturn($result);
            }
        } else if ($id == 2) {
            $res = M('sys_message')->where(['to_user' => $user_id, 'type' => 6])->save(['is_read' => 1]);

            if ($res !== false) {
                $result = ['code' => 200, 'msg' => '操作成功'];
                $this->ajaxReturn($result);
            } else {
                $result = ['code' => 220, 'msg' => '操作失败'];
                $this->ajaxReturn($result);
            }
        } else if ($id == 3) {
            // 启动事务
            M()->startTrans();

            // 准备数据
            $res1 = M('auth_img')->where(['user_id' => $user_id])->save(['is_read' => 1]);
            $res2 = M('packet_img')->where(['user_id' => $user_id])->save(['is_read' => 1]);

            if ($res1 !== false && $res2 !== false) {
                M()->commit();

                $result = ['code' => 200, 'msg' => '操作成功'];
                $this->ajaxReturn($result);
            } else {
                M()->rollback();

                $result = ['code' => 220, 'msg' => '操作失败'];
                $this->ajaxReturn($result);
            }
        } else if ($id == 4) {
            $res = M('pingjia')->where(['to_user' => $user_id])->save(['is_read' => 1]);

            if ($res !== false) {
                $result = ['code' => 200, 'msg' => '操作成功'];
                $this->ajaxReturn($result);
            } else {
                $result = ['code' => 220, 'msg' => '操作失败'];
                $this->ajaxReturn($result);
            }
        } else if ($id == 5) {
            $res = M('sys_message')->where(['to_user' => $user_id, 'type' => ['in', [-1, 14, 16]]])->save(['is_read' => 1]);

            if ($res !== false) {
                $result = ['code' => 200, 'msg' => '操作成功'];
                $this->ajaxReturn($result);
            } else {
                $result = ['code' => 220, 'msg' => '操作失败'];
                $this->ajaxReturn($result);
            }
        } else {
            $result = ['code' => 220, 'msg' => '操作失败,参数id不正确'];
            $this->ajaxReturn($result);
        }
    }

    //申请查看相册拒绝
    public function refuseimg()
    {
        $id = $_REQUEST['id'];

        $user_id = M('img_request')->where(['id' => $id])->getField('user_id');
        $to_user = M('img_request')->where(['id' => $id])->getField('to_user');
        $name = M('user')->where(['id' => $user_id])->getField('name');

        $context = ['name' => $name, 'desc' => "已拒绝你的查看申请", 'type' => 2];
        $arr = [
            'to_user' => $to_user,
            'uid' => $user_id,
            'context' => json_encode($context,JSON_UNESCAPED_UNICODE),
            'type' => 6
        ];
        $res = M('sys_message')->data($arr)->add();

        $res = M('img_request')->where(['id' => $id])->save(['time' => date('Y-m-d H:i:s'), 'state' => 2]);

        if ($res) {
            $result = ['code' => 200, 'msg' => '操作成功'];
            $this->ajaxReturn($result);
        } else {
            $result = ['code' => 220, 'msg' => '操作失败'];
            $this->ajaxReturn($result);
        }
    }

    //领取红包
    public function packet()
    {
        $id = $_REQUEST['user_id'];

        //是否为女性用户
        $sex = M('user')->where(['id' => $id])->getField('sex');
        if ($sex != "女") {
            $this->ajaxReturn(['code' => 220, 'msg' => '女性用户才能领取']);
        }

        //今日是否已领取
        $money = M('packet')->where(['user_id' => $id, 'time' => date("Y-m-d")])->getField('money');
        $money = $money - 0;
        if ($money) {
            $this->ajaxReturn(['code' => 220, 'msg' => '今日已领取']);
        }

        //分享次数达到3次
        $num = M('packet')->where(['user_id' => $id, 'time' => date('Y-m-d')])->getField('num');
        if ($num < 3) {
            $ci = 3 - $num;
            $this->ajaxReturn(['code' => 220, 'msg' => '今日分享再' . $ci . '次即可领取']);
        }

        //身份是否已认证
        $attestation = M('user')->where(['id' => $id])->getField('attestation');
        if (!$attestation) {
            $this->ajaxReturn(['code' => 220, 'msg' => '身份未认证']);
        }

        $moneysum = M('packetsum')->where(['time' => date("Y-m-d")])->getField('money');   //今日红包总额
        $shengyu = M('packetsum')->where(['time' => date("Y-m-d")])->getField('shengyu');  //剩余金额
        $top = M('packetsum')->where(['time' => date("Y-m-d")])->getField('top');             //单个红包上限
        $bottom = M('packetsum')->where(['time' => date("Y-m-d")])->getField('bottom');     //单个红包下限

        $money = mt_rand($bottom * 100, $top * 100);
        $money = $money / 100;
        if ($shengyu < $bottom) {  //剩余总额 小于 单个红包下限
            $this->ajaxReturn(['code' => 220, 'msg' => '红包总剩额不足']);
        } else {
            for ($i = 0; $i < 1; $i++) {
                if ($shengyu < $money) { //剩余红包 小于 开出的红包 但大于单个红包下限 时，重新开个数
                    $money = mt_rand($bottom * 100, $top * 100);
                    $money = $money / 100;
                    $i--;
                }
            }
        }

        $volley = M('user')->where(['id' => $id])->getField('volley');

        // 启动事务
        M()->startTrans();

        // 准备数据
        $res1 = M('packet')->where(['user_id' => $id, 'time' => date("Y-m-d")])->save(['money' => $money, 'ltime' => date('Y-m-d H:i:s')]);//领取红包
        $res2 = M('packetsum')->where(['time' => date("Y-m-d")])->save(['shengyu' => ($shengyu - $money)]);//红包总额扣减
        $res3 = M('packetsum')->where(['time' => date("Y-m-d")])->setInc('cishu');//领取人数+1

        $res4 = M('user')->where(['id' => $id])->save(['volley' => ($volley + $money)]);

        // 记录流水
        M('volley_desc')->add(['user_id' => $id, 'content' => '领取红包', 'price' => $money, 'types' => 1, 'time' => time()]);

        if ($res1 !== false && $res2 !== false && $res3 !== false && $res4 !== false) {
            M()->commit();

            $result = ['code' => 200, 'msg' => '领取红包成功', 'money' => $money];
            $this->ajaxReturn($result);
        } else {
            M()->rollback();

            $result = ['code' => 220, 'msg' => '领取红包失败'];
            $this->ajaxReturn($result);
        }
    }

    //分享页面统计
    public function sharenum()
    {
        $id = $_REQUEST['user_id'];

        $packet = M('packet')->where(['user_id' => $id, 'time' => date("Y-m-d")])->find();

        if (!$packet) {
            $res = M('packet')->add(['user_id' => $id, 'time' => date("Y-m-d"), 'num' => 1]);
        } else {
            $res = M('packet')->where(['user_id' => $id, 'time' => date("Y-m-d")])->setInc('num');
        }

        $cishu = M('packet')->where(['user_id' => $id, 'time' => date("Y-m-d")])->find();
        if ($cishu >= 3) {
            $result = ['code' => 201, 'msg' => '操作成功'];
            $this->ajaxReturn($result);
        }

        if ($res) {
            $result = ['code' => 200, 'msg' => '操作成功'];
            $this->ajaxReturn($result);
        } else {
            $result = ['code' => 220, 'msg' => '操作失败'];
            $this->ajaxReturn($result);
        }
    }

    //忘记密码
    public function forget()
    {
        if (!isset($_REQUEST['phone'])) {
            $this->ajaxReturn(['code' => 220, 'msg' => '操作失败,手机号有误']);
        }

        if (!isset($_REQUEST['password'])) {
            $this->ajaxReturn(['code' => 220, 'msg' => '操作失败,密码有误']);
        }

        $res = M('user')->where(['phone' => $_REQUEST['phone']])->save(['password' => $_REQUEST['password']]);

        if ($res !== false) {
            $this->ajaxReturn(['code' => 200, 'msg' => '操作成功']);
        } else {
            $this->ajaxReturn(['code' => 220, 'msg' => '操作失败']);
        }
    }

    //认证/会员今日查看联系方式次数
    public function vipsee()
    {
        $id = I('user_id');
        $to_user = I('to_user');  //接收人
        $types = I('types') ?: 1;  // 1微信|2QQ|3手机
        
        switch ($types) {
            case 1:
                $field = 'line_price';
                $field_config = 'unblock_wechat';
                break;
            case 2:
                $field = 'qq_price';
                $field_config = 'unblock_qq';
                break;
            case 3:
                $field = 'phone_price';
                $field_config = 'unblock_phone';
                break;
        }
        
        $record = M('vip_num')->where(['user_id' => $id, 'to_user' => $to_user, 'type' => 1, 'types' => $types])->find();

        if ($record) $this->ajaxReturn(['code' => 205, 'msg' => '成功']);
    
        $config = M('config_system')->where(['category' => 'unblock'])->getfield('title,content');

        $user = M('user')->where(['id' => $id])->find();
        $toUser = M('user')->field($field)->where(['id' => $to_user])->find();

        //$money = $toUser[$field] ?: $config[$field_config];
        $money = $config[$field_config];

        if ($user['sex'] == '女') {
            if (!$user['attestation']) {
                $this->ajaxReturn(['code' => 201, 'msg' => '尚未进行真人认证', 'money' => $money]);
            }

            $this->ajaxReturn(['code' => 200, 'msg' => '解锁成功', 'num' => 0]);

            /*$num = M('vip_num')->where(['user_id' => $id, 'type' => 1, 'date' => date("Y-m-d")])->count();
            // $num2 = M('vip_num')->where(['user_id'=>$id,'type'=>4,'date'=>date("Y-m-d")])->count();
            // $num = $num1 + $num2;

            //认证配置权限次数
            $count = M('vip_config')->limit(1)->getfield('count');

            if (!$num) {
                $this->ajaxReturn(['code' => 200, 'msg' => '操作成功', 'num' => $count]);
            } else {
                if ($num >= $count) {
                    $this->ajaxReturn(['code' => 220, 'msg' => '认证用户免费次数今日已使用达到' . $count . '次', 'money' => $money]);
                } else {
                    $this->ajaxReturn(['code' => 200, 'msg' => '操作成功', 'num' => ($count - $num)]);
                }
            }*/
        } else if ($user['sex'] == '男') {
            $state = 0;
            if (!$user['noble_grade'] || $user['noble_time'] < time()) {
                //$this->ajaxReturn(['code' => 202, 'msg' => '非贵族用户', 'money' => $money]);
                $state = 1;
            }
            
            $gradeNoble = M('grade_noble')->where(['grade' => $user['noble_grade']])->find();
            if (!$gradeNoble) {
                //$this->ajaxReturn(['code' => 202, 'msg' => '贵族身份失效', 'money' => $money]);

                $state = 1;
            }
            $privilege = explode(',', $gradeNoble['privilege']);

            if ($state || !in_array(1, $privilege)) {
                $gradeNobleMin = M()->Query("select * from grade_noble where id > 0 and find_in_set(1, privilege) order by grade asc limit 1");

                if ($gradeNobleMin) {
                    $gradeNobleMin = $gradeNobleMin[0];
                    $this->ajaxReturn(['code' => 203, 'msg' => '贵族等级无此特权', 'money' => $money, 'min_noble_grade' => $gradeNobleMin['grade'], 'min_noble_name' => $gradeNobleMin['name']]);
                } else {
                    $this->ajaxReturn(['code' => 203, 'msg' => '贵族等级无此特权', 'money' => $money, 'min_noble_grade' => '', 'min_noble_name' => '']);
                }
            }

            $num = M('vip_num')->where(['user_id' => $id, 'type' => 1, 'date' => date("Y-m-d"), 'is_buy' => 0, 'types' => $types])->count();
            // $num2 = M('vip_num')->where(['user_id'=>$id,'type'=>4,'date'=>date("Y-m-d")])->count();
            // $num = $num1 + $num2;

            //会员配置权限次数
            $max = $config['unblock_noble_max_day'];
            
            if ($num >= $max) {
                $this->ajaxReturn(['code' => 220, 'msg' => '贵族今日次数已达上限' . $max . '次', 'money' => $money]);
            } else {
                $this->ajaxReturn(['code' => 200, 'msg' => '解锁成功', 'num' => ($max - $num)]);
            }
        }
    }

    //认证/会员今日剩余查看付费相册次数
    public function vipimg()
    {
        $id = $_REQUEST['user_id'];
        $to_user = $_REQUEST['to_user'];  //接收人

        if (!$id) {
            $this->ajaxReturn(['code' => 220, 'msg' => '参数user_id不正确']);
        }
        if (!$to_user) {
            $this->ajaxReturn(['code' => 220, 'msg' => '参数to_user不正确']);
        }

        $pd = M('vip_num')->where(['user_id' => $id, 'to_user' => $to_user, 'type' => 3])->select();

        if ($pd) {
            $this->ajaxReturn(['code' => 205, 'msg' => '操作成功']);
        }

        $user = M('user')->where(['id' => $id])->find();

        if ($user['sex'] == '女') {
            if (!$user['attestation']) {
                $this->ajaxReturn(['code' => 201, 'msg' => '非女性认证用户']);
            }

            $num = M('vip_num')->where(['user_id' => $id, 'type' => 3, 'date' => date("Y-m-d")])->count();

            //认证配置权限次数
            $count = M('vip_config')->limit(1)->getfield('count');

            if (!$num) {
                $this->ajaxReturn(['code' => 200, 'msg' => '操作成功', 'num' => $count]);
            } else {
                if ($num >= $count) {
                    $this->ajaxReturn(['code' => 204, 'msg' => '认证用户免费次数今日已使用达到' . $count . '次']);
                } else {
                    $this->ajaxReturn(['code' => 200, 'msg' => '操作成功', 'num' => ($count - $num)]);
                }
            }
        } else if ($user['sex'] == '男') {
            if ($user['vip_end_datetime'] < date('Y-m-d H:i:s')) {
                $this->ajaxReturn(['code' => 202, 'msg' => '非男性会员用户']);
            }

            $num = M('vip_num')->where(['user_id' => $id, 'type' => 3, 'date' => date("Y-m-d")])->count();

            //会员配置权限次数
            $count = M('vip_config')->limit(1)->getfield('count');

            if (!$num) {
                $this->ajaxReturn(['code' => 200, 'msg' => '操作成功', 'num' => $count]);
            } else {
                if ($num >= $count) {
                    $this->ajaxReturn(['code' => 204, 'msg' => '会员免费次数今日已使用达到' . $count . '次']);
                } else {
                    $this->ajaxReturn(['code' => 200, 'msg' => '操作成功', 'num' => ($count - $num)]);
                }
            }
        }
    }

    //认证/会员今日私聊剩余次数
    public function viptalk()
    {
        $id = I('user_id');
        $to_user = I('to_user');  //接收人

        $pd = M('vip_num')->where(['user_id' => $id, 'to_user' => $to_user, 'type' => 4])->select();

        if ($pd) {
            $this->ajaxReturn(['code' => 205, 'msg' => '操作成功']);
        }

        $user = M('user')->where(['id' => $id])->find();

        if ($user['sex'] == '女') {
            if (!$user['attestation']) {
                $this->ajaxReturn(['code' => 201, 'msg' => '非女性认证用户']);
            }

            /*$num = M('vip_num')->where(['user_id'=>$id,'type'=>4,'date'=>date("Y-m-d")])->count();

			//认证配置权限次数
			$count = M('vip_config')->limit(1)->getfield('count');

			if(!$num){
		        $this->ajaxReturn(['code' => 200,'msg' =>'操作成功','num'=>$count]);
			}else {
				if($num >= $count){
					$this->ajaxReturn(['code' => 204,'msg' =>'认证用户免费次数今日已使用达到'.$count.'次']);
				}else {
					$this->ajaxReturn(['code' => 200,'msg' =>'操作成功','num'=>($count-$num)]);
				}
			}*/
            $this->ajaxReturn(['code' => 200, 'msg' => '操作成功', 'num' => 0]);
        } else if ($user['sex'] == '男') {

            if ($user['vip_end_datetime'] < date('Y-m-d H:i:s')) {
                $this->ajaxReturn(['code' => 202, 'msg' => '非会员用户']);
            }

            $num = M('vip_num')->where(['user_id|to_user' => $id, 'type' => 4, 'date' => date("Y-m-d"), 'is_buy' => 0])->count();

            //会员配置权限次数
            $count = M('vip_config')->limit(1)->getfield('count');

            if (!$num) {
                $this->ajaxReturn(['code' => 200, 'msg' => '操作成功', 'num' => $count]);
            } else {
                if ($num >= $count) {
                    $this->ajaxReturn(['code' => 204, 'msg' => '会员免费次数今日已使用达到' . $count . '次']);
                } else {
                    $this->ajaxReturn(['code' => 200, 'msg' => '操作成功', 'num' => ($count - $num)]);
                }
            }
        }
    }

    //非认证/非会员今日查看用户信息次数
    public function vipinfo()
    {
        $id = $_REQUEST['user_id'];

        $user = M('user')->where(['id' => $id])->find();

        if ($user['sex'] == '女') {
            if ($user['attestation']) {
                $this->ajaxReturn(['code' => 200, 'msg' => '女性认证用户，不限次数']);
            }

            $num = M('vip_num')->where(['user_id' => $id, 'type' => 5, 'date' => date("Y-m-d")])->count();

            //认证配置权限次数
            $count = M('vip_config')->order('id desc')->limit(1)->getfield('count');

            if (!$num) {
                if (!$count) {
                    $this->ajaxReturn(['code' => 201, 'msg' => '非认证用户免费次数今日已使用达到' . $count . '次']);
                } else {
                    $this->ajaxReturn(['code' => 200, 'msg' => '操作成功', 'num' => $count]);
                }
            } else {
                if ($num >= $count) {
                    $this->ajaxReturn(['code' => 201, 'msg' => '非认证用户免费次数今日已使用达到' . $count . '次']);
                } else {
                    $this->ajaxReturn(['code' => 200, 'msg' => '操作成功', 'num' => ($count - $num)]);
                }
            }
        } else if ($user['sex'] == '男') {
            if ($user['vip_end_datetime'] > date('Y-m-d H:i:s')) {
                $this->ajaxReturn(['code' => 200, 'msg' => '男性会员用户,不限次数']);
            }

            $num = M('vip_num')->where(['user_id' => $id, 'type' => 5, 'date' => date("Y-m-d")])->count();

            //会员配置权限次数
            $count = M('vip_config')->order('id desc')->limit(1)->getfield('count');

            if (!$num) {
                if (!$count) {
                    $this->ajaxReturn(['code' => 201, 'msg' => '非认证用户免费次数今日已使用达到' . $count . '次']);
                } else {
                    $this->ajaxReturn(['code' => 200, 'msg' => '操作成功', 'num' => $count]);
                }
            } else {
                if ($num >= $count) {
                    $this->ajaxReturn(['code' => 202, 'msg' => '非会员免费次数今日已使用达到' . $count . '次']);
                } else {
                    $this->ajaxReturn(['code' => 200, 'msg' => '操作成功', 'num' => ($count - $num)]);
                }
            }
        }
    }

    //认证/会员今日发布广播剩余次数
    public function vipdymanic()
    {
        $config = M('config_system')->where(['category' => 'dymanic'])->getfield('title, content');

        $id = I('user_id');
        $type = I('type');

        if ($type != 2) {
            if ($type != 6) {
                $this->ajaxReturn(['code' => 220, 'msg' => 'type参数不正确']);
            }
        }

        $user = M('user')->where(['id' => $id])->find();

        if (!$user) {
            $this->ajaxReturn(['code' => 220, 'msg' => '用户不存在']);
        }

        if ($user['sex'] == '女') {
            if (!$user['attestation']) {
                $this->ajaxReturn(['code' => 201, 'msg' => '尚未进行真人认证', 'money' => $config['dymanic_price']]);
            }

            $this->ajaxReturn(['code' => 200, 'msg' => '成功']);

            /*$num = M('vip_num')->where(['user_id' => $id, 'type' => $type, 'date' => date("Y-m-d")])->count();

            //认证配置权限次数
            $count = M('vip_config')->limit(1)->getfield('count');

            if (!$num) {
                $this->ajaxReturn(['code' => 200, 'msg' => '操作成功', 'num' => $count]);
            } else {
                if ($num >= $count) {
                    $this->ajaxReturn(['code' => 204, 'msg' => '认证用户免费次数今日已使用达到' . $count . '次', 'money' => $money]);
                } else {
                    $this->ajaxReturn(['code' => 200, 'msg' => '操作成功', 'num' => ($count - $num)]);
                }
            }*/
        } else if ($user['sex'] == '男') {
            if (!$user['noble_grade'] || $user['noble_time'] < time()) {
                $this->ajaxReturn(['code' => 202, 'msg' => '非贵族用户', 'money' => $config['dymanic_price']]);
            }

            /*$gradeNoble = M('grade_noble')->where(['grade' => $user['noble_grade']])->find();
            if (!$gradeNoble) {
                $this->ajaxReturn(['code' => 202, 'msg' => '贵族身份失效', 'money' => $money]);
            }*/

            $num = M('vip_num')->where(['user_id' => $id, 'type' => $type, 'date' => date("Y-m-d")])->count();

            $max = $config['noble_max_day'];

            if ($num >= $max) {
                $this->ajaxReturn(['code' => 204, 'msg' => '贵族今日次数已达上限' . $max . '次', 'money' => $config['dymanic_price']]);
            } else {
                $this->ajaxReturn(['code' => 200, 'msg' => '成功', 'num' => ($max - $num)]);
            }
        }
    }

    //私聊权限使用1次
    public function Inctalk()
    {
        $user_id = $_REQUEST['user_id'];  //发送人
        $to_user = $_REQUEST['to_user'];  //接受人

        // if(!$user_id) {
        // 	$this->ajaxReturn(['code' => 220,'msg' =>'操作失败,参数user_id不正确']);
        // }

        // if(!$to_user) {
        // 	$this->ajaxReturn(['code' => 220,'msg' =>'操作失败,参数to_user不正确']);
        // }

        $num = M('vip_num')->where(['user_id' => $user_id, 'to_user' => $to_user, 'type' => 4])->find();
        if ($num) {
            $this->ajaxReturn(['code' => 200, 'msg' => '已有私聊记录，私聊免费次数不减1']);
        }

        $res = M('vip_num')->add(['user_id' => $user_id, 'to_user' => $to_user, 'type' => 4, 'date' => date("Y-m-d")]);

        if ($res) {
            $this->ajaxReturn(['code' => 200, 'msg' => '操作成功,私聊权限使用1次']);
        } else {
            $this->ajaxReturn(['code' => 200, 'msg' => '操作失败']);
        }
    }

    //相册权限使用1次
    public function Incxiang()
    {
        $user_id = $_REQUEST['user_id'];  //查看人
        $to_user = $_REQUEST['to_user'];  //被查看人

        if (!$user_id) {
            $this->ajaxReturn(['code' => 220, 'msg' => '操作失败,参数user_id不正确']);
        }

        if (!$to_user) {
            $this->ajaxReturn(['code' => 220, 'msg' => '操作失败,参数to_user不正确']);
        }

        $num = M('vip_num')->where(['user_id' => $user_id, 'to_user' => $to_user, 'type' => 3, 'date' => date("Y-m-d")])->find();
        if ($num) {
            $this->ajaxReturn(['code' => 220, 'msg' => '今日已有查看相册记录，私聊免费次数不减1']);
        }

        $res = M('vip_num')->add(['user_id' => $user_id, 'to_user' => $to_user, 'type' => 3, 'date' => date("Y-m-d")]);
        M('auth_img')->add(['user_id' => $to_user, 'to_user' => $user_id, 'price' => 0]);  //一样写进查看收费相册记录表中
        $name = M('user')->where(['id' => $to_user])->getField('name');
        $context = ['name' => $name, 'time' => time(), 'price' => 0.00, 'type' => 1];
        $context = json_encode($context);
        $arr = [
            'to_user' => $to_user,
            'uid' => $user_id,
            'context' => $context,
            'type' => 7
        ];
        M('sys_message')->add($arr);
        if ($res) {
            $this->ajaxReturn(['code' => 200, 'msg' => '操作成功,查看相册权限使用1次']);
        } else {
            $this->ajaxReturn(['code' => 220, 'msg' => '操作失败']);
        }
    }

    //查看联系方式权限使用1次
    public function Inclian()
    {
        $user_id = $_REQUEST['user_id'];  //查看人
        $to_user = $_REQUEST['to_user'];  //被查看人

        // if(!$user_id) {
        // 	$this->ajaxReturn(['code' => 220,'msg' =>'操作失败,参数user_id不正确']);
        // }

        // if(!$to_user) {
        // 	$this->ajaxReturn(['code' => 220,'msg' =>'操作失败,参数to_user不正确']);
        // }

        $num = M('vip_num')->where(['user_id' => $user_id, 'to_user' => $to_user, 'type' => 1])->find();
        if ($num) {
            $this->ajaxReturn(['code' => 200, 'msg' => '已有查看联系方式记录，私聊免费次数不减1']);
        }

        $res = M('vip_num')->add(['user_id' => $user_id, 'to_user' => $to_user, 'type' => 1, 'date' => date("Y-m-d")]);

        if ($res) {

            $name = M('user')->where(['id' => $user_id])->getField('name');

            $context = ['name' => $name, 'desc' => "你已获取了" . $name . "的联系方式,去评价Ta吧"];
            $arr = [
                'to_user' => $user_id,
                'uid' => $to_user,
                'context' => json_encode($context),
                'type' => 15
            ];
            M('sys_message')->data($arr)->add();

            $this->ajaxReturn(['code' => 200, 'msg' => '操作成功,查看联系方式使用1次']);
        } else {
            $this->ajaxReturn(['code' => 200, 'msg' => '操作失败']);
        }
    }

    //付费查看联系方式
    public function buylian()
    {
        $user_id = I('user_id');  //查看人
        $to_user = I('to_user');  //被查看人
        $types = I('types');      // 1微信|2QQ|3手机


        $num = M('vip_num')->where(['user_id' => $user_id, 'to_user' => $to_user, 'type' => 1, 'types' => $types])->find();
        if ($num) {
            $this->ajaxReturn(['code' => 203, 'msg' => '已经购买']);
        }

        switch ($types) {
            case 1:
                $field_config = 'unblock_wechat';
                break;
            case 2:
                $field_config = 'unblock_qq';
                break;
            case 3:
                $field_config = 'unblock_phone';
                break;
        }

        $config = M('config_system')->where(['title' => $field_config])->getfield('title,content');

        $money = $config[$field_config];

        $qian = M('user')->where('id=' . $user_id)->find();

        if ($qian['volley'] < $money) {
            $this->ajaxReturn(['code' => 201, 'msg' => '余额不足']);
        }

        $res = M('vip_num')->add(['user_id' => $user_id, 'to_user' => $to_user, 'type' => 1, 'types' => $types, 'date' => date("Y-m-d"), 'is_buy' => 1]);

        if ($res) {
            D('VolleyDesc')->index($user_id, $money * 1, '解锁联系方式');
            D('YaoqingRecords')->index($to_user, $user_id, $money * 1, '解锁联系方式');

            $this->ajaxReturn(['code' => 200, 'msg' => '解锁成功']);
        } else {
            $this->ajaxReturn(['code' => 204, 'msg' => '解锁失败']);
        }
    }

    //点击获取联系方式
    public function getlink()
    {
        $user_id = $_REQUEST['to_user'];  //被查看人
        $to_user = $_REQUEST['user_id'];  //查看人
        $types = I('types') ?: 1;  // 1微信|2QQ|3手机
    
        switch ($types) {
            case 1:
                $field = 'wxcount';
                $msg = '微信账号';
                break;
            case 2:
                $field = 'qq';
                $msg = 'QQ账号';
                break;
            case 3:
                $field = 'phone';
                $msg = '手机号码';
                break;
        }

        $user = M('user')->where(['id' => $user_id])->find();

        if (!$user) {
            $this->ajaxReturn(['code' => 220, 'msg' => '查看的用户不存在']);
        }

        $data = [
            'name' => $user['name'],
            'head_portrait' => $user['head_portrait'],
            'head_300' => $user['head_300'],
            'line' => $user[$field],
            'self_slogan' => $user['self_slogan'],
        ];

        $num = M('vip_num')->where(['user_id' => $to_user, 'to_user' => $user_id, 'type' => 1, 'types' => $types])->find();
        if (!$num) {
            M('vip_num')->add(['user_id' => $to_user, 'to_user' => $user_id, 'type' => 1, 'date' => date("Y-m-d"), 'types' => $types]);
        }

        $name = M('user')->where(['id' => $to_user])->getField('name');

        // 推送
        /*$datas = json_encode(['type' => 8, 'userid' => $to_user, 'name' => $name], JSON_UNESCAPED_UNICODE);
        D('Push')->send(8, $user_id, '消息提醒', "{$name} 请求查看你的{$msg}", $datas);*/

        $this->ajaxReturn(['code' => 200, 'msg' => '操作成功', 'data' => $data]);
    }

    //发送联系方式
    public function sendlink()
    {
        $user_id = $_REQUEST['user_id'];  //发送人
        $to_user = $_REQUEST['to_user'];  //接收人

        $name = M('user')->where(['id' => $user_id])->getfield('name');
        $context = ['name' => $name, 'desc' => $name . '给你发送Ta的社交账号'];
        $arr = [
            'to_user' => $to_user,
            'uid' => $user_id,
            'context' => json_encode($context,JSON_UNESCAPED_UNICODE),
            'type' => 10
        ];

        M('sys_message')->data($arr)->add();

        // 推送
        /*$datas = json_encode(['type' => 10, 'userid' => $user_id, 'name' => $name], JSON_UNESCAPED_UNICODE);
        D('Push')->send(10, $to_user, '消息提醒', "你收到 {$name} 发过来的社交账号", $datas);*/

        $this->ajaxReturn(['code' => 200, 'msg' => '发送成功']);
    }

    //查看邀请码
    public function seecode()
    {
        if (isset($_REQUEST['phone'])) {
            $user = M('user')->where(['phone' => $_REQUEST['phone']])->find();
        } else if (isset($_REQUEST['wechat'])) {
            $user = M('user')->where(['wechat' => $_REQUEST['wechat']])->find();
        } else if (isset($_REQUEST['qq_openID'])) {
            $user = M('user')->where(['qq_openID' => $_REQUEST['qq_openID']])->find();
        }

        if ($user) {
            if ($user['reg']) {
                $this->ajaxReturn(['code' => 220, 'msg' => '此账号已注册，无需申请邀请码']);
            } else {
                $code = M('code')->where(['user_id' => $user['id']])->order('time desc')->find();
                if (!$code['type']) {
                    $this->ajaxReturn(['code' => 220, 'msg' => '申请邀请码审核中']);
                } else {
                    $this->ajaxReturn(['code' => 200, 'msg' => '申请邀请码审核通过', 'invite' => $code['code']]);
                }
            }
        } else {
            $this->ajaxReturn(['code' => 220, 'msg' => '此手机账号未有申请记录']);
        }
    }

    //查看联系方式信息 或 发布广播 或 私聊 收费
    public function chaoe()
    {
        $user_id = $_REQUEST['user_id'];   //被查看用户ID
        $to_user = $_REQUEST['to_user'];   //操作用户ID
        $price = $_REQUEST['price'];       //价格
        $type = $_REQUEST['type'];
        $types = I('types');
        
        if ($price < 0) {
            $this->ajaxReturn(['code' => 220, 'msg' => '操作有误']);
        }

        if (in_array($type, [2, 3])) {//查看联系方式信息 私聊
            $where = [
                'user_id' => $to_user,
                'to_user' => $user_id,
                'type' => $type,
            ];
            
            if ($type == 2) {
                $where['types'] = $types;
            }
            $result = M('chaoe')->where($where)->find();

            if ($result) {
                $this->ajaxReturn(['code' => 220, 'msg' => '已支付过，无需重复操作']);
            }
        }

        $volley = M('user')->where('id=' . $to_user)->getField('volley');

        if ($volley < $price) {
            $this->ajaxReturn(['code' => 220, 'msg' => '余额不足']);
        } else {
            $volley = $volley - $price;

            if ($type == 1) {
                $data = [
                    'user_id' => $to_user,
                    'type' => $type,
                    'price' => $_REQUEST['price']
                ];
            } else if (in_array($type, [2, 3])) {
                $data = [
                    'user_id' => $to_user,
                    'to_user' => $user_id,
                    'type' => $type,
                    'price' => $_REQUEST['price']
                ];
                if ($type == 2) {
                    $data['types'] = $types;
                }

                $name = M('user')->where(['id' => $user_id])->getField('name');
                $context = ['name' => $name, 'time' => time(), 'price' => $_REQUEST['price']];
                $arr = [
                    'to_user' => $user_id,
                    'uid' => $to_user,
                    'context' => json_encode($context),
                    'type' => 16
                ];
            }
            
            M('sys_message')->add($arr);

            // 启动事务
            M()->startTrans();

            // 准备数据

            $res2 = M('chaoe')->add($data);

            switch ($type) {
                case 1:
                    $content = '发布动态';
                    break;
                case 2:
                    $content = '查看联系方式';
                    break;
                case 3:
                    $content = '私聊';
                    break;
            }

            D('VolleyDesc')->index($to_user, $price, $content);

            if ($res2 !== false) {
                M()->commit();

                $this->ajaxReturn(['code' => 200, 'data' => $data, 'msg' => '成功']);
            } else {
                M()->rollback();

                $this->ajaxReturn(['code' => 220, 'msg' => '失败']);
            }
        }
    }

    /**
     * 收费价格
     */
    public function config()
    {
        $data = M('num_config')->select();

        exit(json_encode(['code' => 200, 'data' => $data]));
    }

    //启动图
    public function start()
    {
        $riqi = date("Y-m-d");
        $image = M('start')->where(['start' => ['egt', $riqi], 'end' => ['elt', $riqi]])->find();

        $id = $_REQUEST['user_id'];

        $openHB = 1;


        //是否为女性用户
        $sex = M('user')->where(['id' => $id])->getField('sex');
        if ($sex != "女") {
            $openHB = 0;
        }

        //今日是否已领取
        $money = M('packet')->where(['user_id' => $id, 'time' => date("Y-m-d")])->getField('money');

        $money = $money - 0;
        if ($money) {
            $openHB = 0;
        }

        // //分享次数达到3次
        // $num = M('packet')->where(['user_id'=>$id,'time'=>date('Y-m-d')])->getField('num');
        // if($num < 3) {
        // 	$ci = 3 - $num;
        // 	$this->ajaxReturn(['code' => 220,'msg' =>'今日分享再'.$ci.'次即可领取']);
        // }

        //身份是否已认证
        $attestation = M('user')->where(['id' => $id])->getField('attestation');
        if (!$attestation) {
            $openHB = 0;
        }


        if (!$id) {
            $openHB = 0;
        }

        //今日是否设置红包
        $moneytoday = M('packetsum')->where(['time' => date("Y-m-d")])->find();
        if (!$moneytoday) {
            $openHB = 0;
        }

        $image['openHB'] = $openHB;

        if ($image) {
            $this->ajaxReturn(['code' => 200, 'msg' => 'true', 'data' => $image]);
        } else {
            $this->ajaxReturn(['code' => 200, 'msg' => 'error']);
        }
    }

    public function sel()
    {
        $phone = I('phone');
        if (!$phone) {
            $this->ajaxReturn(['code' => 202, 'msg' => '手机号不能为空']);
        }
        $res = M('user')->where(['phone' => $phone, 'reg' => 1])->find();

        if ($res) {
            /*if (!$res['reg']) {
                M('user')->where('phone=' . $phone)->delete();
                $this->ajaxReturn(['code' => 200, 'msg' => '手机号未注册']);
            }*/
            $this->ajaxReturn(['code' => 202, 'msg' => '手机号已注册']);
        } else {
            $this->ajaxReturn(['code' => 200, 'msg' => '手机号未注册']);
        }
    }

    public function tags()
    {
        $sex = I('sex');
        if ($sex == 1) {
            $tags = M('tags')->where(['type' => '1'])->getField('name', true);
        } else if ($sex == 2) {
            $tags = M('tags')->where(['type' => '2'])->getField('name', true);
        } else {
            $tags = [];
            $tags['man'] = M('tags')->where(['type' => '1'])->getField('name', true);
            $tags['woman'] = M('tags')->where(['type' => '2'])->getField('name', true);
        }

        $this->ajaxReturn(['code' => 200, 'msg' => 'success', 'data' => $tags]);
    }

    // 记录用户查看阅读即焚的照片时手机操作截屏照片
    public function screenshotRecord()
    {
        $user_id = I('user_id');

        if ($user_id) {
            $data = M('screenshot_records')->where(['user_id' => $user_id])->find();

            try {
                if ($data) {
                    M('screenshot_records')->where(['id' => $data['id']])->save([
                        'num' => $data['num'] + 1,
                        'status' => 0,
                        'update_time' => time()
                    ]);
                } else {
                    $current_time = time();
                    M('screenshot_records')->add([
                        'num' => 1,
                        'create_time' => $current_time,
                        'update_time' => $current_time
                    ]);
                }
            } catch (\Exception $e) {
                exit(json_encode(['code' => 201, 'msg' => $e->getMessage()]));
            }

            exit(json_encode(['code' => 200, 'msg' => 'success']));
        }
    }
}
